package com.hailiao.beidou.message.ui.page.search

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hailiao.beidou.message.data.db.entity.MessageEntity
import com.hailiao.beidou.message.data.message.MessageRepository
import com.hailiao.beidou.message.ui.page.destinations.ChatScreenDestination
import com.hailiao.beidou.message.ui.page.navArgs
import com.hailiao.beidou.message.utils.go
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

/**
 * 搜索详情
 * @Author d10ng
 * @Date 2024/3/2 15:10
 */
data class SearchDetailScreenNavArgs(
    val number: String,
    val name: String,
    val key: String
)

class SearchDetailScreenViewModel(
    savedStateHandle: SavedStateHandle
): ViewModel() {

    private val navArgs = savedStateHandle.navArgs<SearchDetailScreenNavArgs>()

    // 用户名
    val nameFlow = MutableStateFlow(navArgs.name)
    // 消息列表
    val messagesFlow = MutableStateFlow(listOf<MessageEntity>())

    init {
        viewModelScope.launch {
            messagesFlow.value = MessageRepository.search(navArgs.number, navArgs.key)
        }
    }

    /**
     * 点击消息
     * @param value MessageEntity
     */
    fun onClickItem(value: MessageEntity) {
        viewModelScope.launch {
            // 查询消息在全部消息中的位置
            val position = MessageRepository.countByTime(value.number, value.createTime)
            // 跳转到聊天界面
            go(ChatScreenDestination(value.number, position.toInt()).route)
        }
    }
}